import { useState } from 'react'

interface KeyMap {
  [key: string]: boolean
}

interface StoreItem {
  value: any,
  dispatch: Set<any>
}

interface Store {
  [key: string]: StoreItem
}

const isInitStore: KeyMap = {}
const store: Store = {}

function _setValue(key: string, value: any) {
  store[key].value = value
  store[key].dispatch.forEach((cb: any) => {
    cb(value)
  })
}

// like subscribe
export function useSubscribe(key: string, value?: any) {
  const [state, setState] = useState(value || null)

  // 如果没有被初始化，则初始化一次
  if (!isInitStore[key]) {
    store[key] = { value: value, dispatch: new Set() }
    isInitStore[key] = true
  }

  if (store[key].dispatch.has(setState) === false) {
    store[key].dispatch.add(setState)
  }

  return [state, (_value: any) => _setValue(key, _value)]
}

export function useDispatch(key: string) {
  return (value: any) => _setValue(key, value)
}